##################################################################
# File : /lua/usersync.lua
# Description : UI Side Sync
# Author : GPG
##################################################################

# The global sync table is copied from the sim layer every time the main and sim threads are
# synchronized on the sim beat (which is like a tick but happens even when the game is paused)
Sync = {}

# The PreviousSync table holds just what you'd expect it to, the sync table from the previous
# beat.
PreviousSync = {}

# Entity specific data that's been sync'd. Data changes are accumulated by merging
# the Sync.EntityData table into this table each sync (if there's new data)
EntityData = {}

BlipMap = {}

SyncCallback = Callback()

# Here's an opportunity for user side script to examine the Sync table for the new tick
function OnSync()

    if Sync.RequestingExit then
        #LOG("Got it")
        ExitGame()
    end

    #Play Sounds
    for k, v in Sync.Sounds do
        PlaySound(Sound{ Bank=v.Bank, Cue=v.Cue })
    end

    #Play Voices
    for k, v in Sync.Voice do
        PlayVoice(Sound{ Bank=v.Bank, Cue=v.Cue }, true)
    end

    # Play ally/enemy sounds
    if Sync.ArmySounds and GetFocusArmy() != -1 then
        for k, v in Sync.ArmySounds do
            if IsAlly(GetFocusArmy(), v.Army) then
                if v.AllySound then
                    PlaySound(v.AllySound)
                end
            else
                if v.EnemySound then
                    PlaySound(v.EnemySound)
                end
            end
        end
    end

    if Sync.ToggleGamePanels then
        ConExecute('UI_ToggleGamePanels')
    end

    if Sync.ToggleLifeBarsOff then
        ConExecute('UI_RenderUnitBars false')
    end

    if Sync.ToggleLifeBarsOn then
        ConExecute('UI_RenderUnitBars true')
    end

    if Sync.UserConRequests then
        for num, execRequest in Sync.UserConRequests do
            ConExecute(execRequest)
        end
    end

    if not table.empty(Sync.EntityData) then
        for id,entData in Sync.EntityData do
            if entData then
                if not EntityData[id] then
                    EntityData[id] = {}
                end
                for k,v in entData do
                    if k == "Inventory" then
                        local blarge = true
                    end
                    EntityData[id][k] = v
                end
            end
        end
    end

    for id,v in Sync.ReleaseIds do
        EntityData[id] = nil
    end

    BlipMap = table.merged(BlipMap,Sync.BlipMap)

    SyncCallback:Call()
end